/**
 * LeanCloud配置和API封装
 * 
 * LeanCloud是一个Serverless后端服务，提供云数据库、云存储等功能
 * 本文件用于配置LeanCloud SDK并封装常用的API操作
 */

import axios from 'axios';

// LeanCloud应用配置
export const LC_APP_ID = '8ncZIxz9jQxXojGXbN7FTqtL-gzGzoHsz';
export const LC_APP_KEY = 'mdM0NvdZYrI02Fee4F0zVkiN';
export const LC_SERVER_URL = 'https://8nczixz9.lc-cn-n1-shared.com';

// 创建axios实例
const leancloudApi = axios.create({
  baseURL: LC_SERVER_URL,
  headers: {
    'Content-Type': 'application/json',
    'X-LC-Id': LC_APP_ID,
    'X-LC-Key': LC_APP_KEY
  }
});

/**
 * 初始化LeanCloud SDK
 */
export function initLeanCloud() {
  console.log('LeanCloud API 初始化完成');
}

/**
 * 用户认证相关API
 */
export const authAPI = {
  /**
   * 用户登录
   * @param username 用户名
   * @param password 密码
   */
  login: async (username: string, password: string) => {
    try {
      const response = await leancloudApi.post('/1.1/login', {
        username,
        password
      });
      return { 
        success: true, 
        userId: response.data.objectId, 
        username: response.data.username,
        sessionToken: response.data.sessionToken
      };
    } catch (error) {
      console.error('登录失败:', error);
      return { success: false, error };
    }
  },
  
  /**
   * 用户注销
   */
  logout: async () => {
    try {
      await leancloudApi.post('/1.1/logout');
      return { success: true };
    } catch (error) {
      console.error('注销失败:', error);
      return { success: false, error };
    }
  },
  
  /**
   * 获取当前用户
   */
  getCurrentUser: async () => {
    try {
      const response = await leancloudApi.get('/1.1/users/me');
      return response.data;
    } catch (error) {
      console.error('获取当前用户失败:', error);
      return null;
    }
  },
  
  /**
   * 用户注册
   * @param username 用户名
   * @param password 密码
   */
  register: async (username: string, password: string) => {
    try {
      const response = await leancloudApi.post('/1.1/users', {
        username,
        password
      });
      return {
        success: true,
        userId: response.data.objectId,
        username: response.data.username
      };
    } catch (error) {
      console.error('注册失败:', error);
      return { success: false, error };
    }
  }
};

/**
 * 数据操作相关API
 */
export const dataAPI = {
  /**
   * 查询指定类的数据
   * @param className 类名
   * @param query 查询条件
   * @param include 需要 include 的 pointer 字段
   */
  query: async (className: string, query: any = {}, include?: string, limit?: number, skip?: number) => {
    try {
      const params: any = { where: JSON.stringify(query) };
      if (include) params.include = include;
      if (limit !== undefined) params.limit = limit;
      if (skip !== undefined) params.skip = skip;
      const response = await leancloudApi.get(`/1.1/classes/${className}`, { params });
      return response.data.results;
    } catch (error) {
      console.error(`查询${className}失败:`, error);
      return [];
    }
  },
  
  /**
   * 获取指定ID的对象
   * @param className 类名
   * @param objectId 对象ID
   */
  get: async (className: string, objectId: string) => {
    try {
      const response = await leancloudApi.get(`/1.1/classes/${className}/${objectId}`);
      return response.data;
    } catch (error) {
      console.error(`获取${className}:${objectId}失败:`, error);
      return null;
    }
  },
  
  /**
   * 保存对象
   * @param className 类名
   * @param data 数据对象
   */
  save: async (className: string, data: any) => {
    try {
      if (data.objectId) {
        // 更新
        const { objectId, ...updateData } = data;
        await leancloudApi.put(`/1.1/classes/${className}/${objectId}`, updateData);
        return { ...data };
      } else {
        // 新增
        const response = await leancloudApi.post(`/1.1/classes/${className}`, data);
        return { ...data, objectId: response.data.objectId };
      }
    } catch (error) {
      console.error(`保存${className}数据失败:`, error);
      return null;
    }
  },
  
  /**
   * 删除对象
   * @param className 类名
   * @param objectId 对象ID
   */
  delete: async (className: string, objectId: string) => {
    try {
      await leancloudApi.delete(`/1.1/classes/${className}/${objectId}`);
      return { success: true };
    } catch (error) {
      console.error(`删除${className}:${objectId}失败:`, error);
      return { success: false, error };
    }
  }
};

/**
 * 文件操作相关API
 */
export const fileAPI = {
  /**
   * 上传文件
   * @param file 文件对象
   * @param fileName 文件名
   */
  upload: async (file: File, fileName: string = file.name) => {
    try {
      const formData = new FormData();
      formData.append('file', file);
      const response = await leancloudApi.post('/1.1/files/' + fileName, formData);
      return { url: response.data.url };
    } catch (error) {
      console.error(`上传文件失败:${fileName}`, error);
      return { success: false, error };
    }
  },
  
  /**
   * 删除文件
   * @param url 文件URL
   */
  delete: async (url: string) => {
    try {
      const fileName = url.split('/').pop();
      await leancloudApi.delete('/1.1/files/' + fileName);
      return { success: true };
    } catch (error) {
      console.error(`删除文件失败:${url}`, error);
      return { success: false, error };
    }
  }
}; 